#!/usr/bin/env python
# -*- coding: utf-8 -*-
from uidesign.MainWindow_ui import Ui_MainWindow
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from .CoffeForm import CoffeForm
from rosservice.NavControl import NavControl
import rospy

class ItemDelegate(QItemDelegate):
    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        column = index.column()
        if column == 0:
            editor.addItems(sorted(NavControl.m_target_point_maps_.keys()))
        # elif column == 4:
        #     editor.addItems(["已下单", "已制作", "派送中", "完成"])
        return editor

    def setEditorData(self, editor, index):
        value = index.data()
        editor.setCurrentText(value)

    def setModelData(self, editor, model, index):
        value = editor.currentText()
        model.setData(index, value)


class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("导览控制系统V1.0.0")
        self.tableWidget.setColumnWidth(0, 80)
        self.tableWidget.setColumnWidth(1, 200)
        # self.tableWidget.setColumnWidth(2, 80)
        delegate = ItemDelegate()
        self.tableWidget.setItemDelegateForColumn(0, delegate)
        # self.tableWidget.setItemDelegateForColumn(4, delegate)

        # self.tableWidget.setColumnWidth(3, 60)
        # self.tableWidget.setColumnWidth(4, 80)
        self.setFixedWidth(800)
        self.setFixedHeight(400)
        self.pushButton.clicked.connect(self.load_all_and_publish)
        self.pushButton_2.clicked.connect(self.open_path_form)
        self.pushButton_3.clicked.connect(self.delete_row)
        self.pushButton_4.clicked.connect(self.parse_nav_path)
        self.pushButton_5.clicked.connect(self.start_nav)
        self.pushButton_6.clicked.connect(self.stop_nav)

        self.set_center()
        self.nav_control = NavControl(self.plainTextEdit)

    def handle_message(self, message):
        self.plainTextEdit.appendPlainText(message)

    def stop_nav(self):
        self.nav_control.stop_nav()

    def start_nav(self):
        self.nav_control.start_nav()

    def load_all_and_publish(self):
        self.nav_control.load_and_publish()

    def parse_nav_path(self):
        points = self.build_path_points_from_table()
        # print(points)
        if len(points) < 2:
            QMessageBox.information(self, "提示", "最少需要添加两个导览点")
            return
        self.nav_control.parse_nav_path(points)

    def build_path_points_from_table(self):
        rows = self.tableWidget.rowCount()
        cols = self.tableWidget.columnCount()
        data = []
        for r in range(rows):
            row_data = []
            for c in range(cols):
                item = self.tableWidget.item(r, c)
                if item is not None:
                    row_data.append(item.text())
                else:
                    row_data.append('')
            data.append(row_data)
        return map(lambda row: {"name": row[0], "message": row[1]}, data)

    def open_path_form(self):
        if NavControl.m_target_point_maps_ is None or len(NavControl.m_target_point_maps_) == 0:
            QMessageBox.information(self, "提示", "请先加载全部的导览点")
            return
        if not hasattr(self, "dialog"):
            self.coffe_form = CoffeForm(self)
            self.coffe_form.setWindowModality(Qt.ApplicationModal)
        else:
            self.coffe_form.clear()
        self.coffe_form.show()

    def delete_row(self):
        cRow = self.tableWidget.currentRow()
        if cRow == -1:
            QMessageBox.information(self, "提示", "请先左键单击要删除行")
            return
        ans = QMessageBox.question(self, "确认", "是否要删除第" + str(cRow + 1) + "行?",
                                   QMessageBox.Yes | QMessageBox.No)
        if ans == QMessageBox.Yes:
            self.tableWidget.removeRow(cRow)

    def append_row(self, arr):
        row_count = self.tableWidget.rowCount()
        col_count = self.tableWidget.columnCount()
        self.tableWidget.setRowCount(row_count + 1)
        # assert col_count == len(arr), "参数数量和列数不一致"
        for i in range(col_count):
            if i > 1:
                continue
            cell_text = str(arr[i])
            new_item = QTableWidgetItem(cell_text)
            new_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            self.tableWidget.setItem(row_count, i, new_item)

    def set_center(self):
        screen = QtWidgets.QDesktopWidget().screenGeometry()
        size = self.geometry()
        new_left = (screen.width() - size.width()) / 2
        new_top = (screen.height() - size.height()) / 2
        self.move(int(new_left), int(new_top))


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
